﻿namespace Sai.Core.Reporting
{
	using System.Text;

	public class TagContentReplacer
	{
		public TagContentReplacer(string tagName)
		{
			this.StartTag = string.Format("<{0}", tagName);
			this.EndTag = string.Format("</{0}>", tagName);
		}

		private string StartTag { get; set; }

		private string EndTag { get; set; }

		public string ReplaceWith(string wholeContent, string newTagContent)
		{
            const int NotFound = -1;
			int startOfTag = wholeContent.IndexOf(this.StartTag);

			if (startOfTag != NotFound)
			{
				int startOfEndTag = wholeContent.IndexOf(this.EndTag, startOfTag);

				string newStartTag = this.StartTag;

                // does it have a matching closing tag?
                if (startOfEndTag == NotFound)
                {
                    const string EmptyTagClose = "/>";
                    startOfEndTag = wholeContent.IndexOf(EmptyTagClose, startOfTag) + EmptyTagClose.Length;
					newStartTag = wholeContent.Substring(startOfTag, startOfEndTag - startOfTag - EmptyTagClose.Length);
                }
                else
                {
                    const string TagClose = ">";
                    int endOfTag = wholeContent.IndexOf(TagClose, startOfTag);
					newStartTag = wholeContent.Substring(startOfTag, endOfTag - startOfTag);
                    startOfEndTag += this.EndTag.Length;
                }

				var builder = new StringBuilder();
				builder.Append(wholeContent.Substring(0, startOfTag));
				builder.Append(string.Concat(newStartTag, ">"));
                builder.Append(newTagContent);
                builder.Append(this.EndTag);
                builder.Append(wholeContent.Substring(startOfEndTag));

				return builder.ToString();
            }

			return wholeContent;
		}
	}
}
